package com.qf.rabbitmq2203.consumer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.rabbitmq2203.constants.Constants;
import com.qf.rabbitmq2203.entity.Vote;
import com.qf.rabbitmq2203.water.entity.Waterlist;
import com.qf.rabbitmq2203.water.service.IWaterlistService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class Myconsumer {

    @Autowired
    IWaterlistService waterlistService;

    @RabbitListener(queues = "vote")
    public void saveDatabase(String json ,Channel channel, Message message) throws IOException {

        System.out.println(json);


        ObjectMapper objectMapper = new ObjectMapper();

        final List<Vote> votes = objectMapper.readValue(json, new TypeReference<List<Vote>>(){});

        Waterlist waterlist = new Waterlist();

        ArrayList<Waterlist> waterlists = new ArrayList<>();

        for (Vote vote : votes) {
            Integer candidateId = vote.getCandidateId();
            Date updateTime = vote.getUpdateTime();
            String phone = vote.getPhone();

            waterlist.setCandidateId(candidateId);
            waterlist.setUpdateTime(updateTime);
            waterlist.setPhone(phone);

            waterlists.add(waterlist);

        }

        waterlistService.saveBatch(waterlists);

        //手工ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);


    }


    @RabbitListener(queues = Constants.DEAD_LETTER_QUEUE_A)
    public void getMsg(String msg, Channel channel, Message message) throws IOException {

        System.out.println(msg);

        //手工ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
